package br.ufpe.cin.dsoa.handler.dependency;

import java.util.ArrayList;
import java.util.Dictionary;
import java.util.List;

import org.apache.felix.ipojo.ConfigurationException;
import org.apache.felix.ipojo.PrimitiveHandler;
import org.apache.felix.ipojo.metadata.Element;
import org.apache.felix.ipojo.parser.FieldMetadata;
import org.apache.felix.ipojo.parser.PojoMetadata;

import br.ufpe.cin.dsoa.common.Constants;
import br.ufpe.cin.dsoa.manager.AdaptationManager;


public class DependencyHandler extends PrimitiveHandler {
	
	/**
	 * Tag handler
	 */
	public static final String NAMESPACE = "br.ufpe.cin.dsoa.handler";
	public static final String NAME      = "requires";
	
	private AdaptationManager dsoaAdaptationManager;

	@SuppressWarnings("rawtypes")
	@Override
	public void configure(Element metadata, Dictionary configuration)
			throws ConfigurationException {
		
		
		Element      requires     = metadata.getElements(NAME, NAMESPACE)[0];
		PojoMetadata pojoMetadata = getFactory().getPojoMetadata();
		FieldMetadata fieldMetadata;
		String applicationId = requires.getAttribute(Constants.CONSUMER_PID_ATTRIBUTE);
		
		Element[] serviceElems = requires.getElements(Constants.SERVICE_ELEMENT);
		List<Dependency> dependencies = new ArrayList<Dependency>();
		this.dsoaAdaptationManager.setDsoaDependencyHandler(this);
		for (Element serviceTag : serviceElems) {
			String fieldMetaName = serviceTag.getAttribute(Constants.SERVICE_FIELD_ATTRIBUTE);
			fieldMetadata = pojoMetadata.getField(fieldMetaName);
			
			Class spec = null;
	        try {
	            spec = getInstanceManager().getContext().getBundle().loadClass(fieldMetadata.getFieldType());
	        } catch (ClassNotFoundException e) {
	            throw new ConfigurationException("A required specification cannot be loaded : " + fieldMetadata.getFieldType());
	        }
			
			DependencyMetadata dependencyMetadata = new DependencyMetadata(spec, serviceTag);
			Dependency dependency = new Dependency(dependencyMetadata, dependencyMetadata.getSlos());
			dependencies.add(dependency);
			// register the service field
			getInstanceManager().register(fieldMetadata, dependency);
			this.dsoaAdaptationManager.manageDependecy(applicationId, dependency);	
		}
	}
	
	@Override
	public void start() {
		this.setValidity(false);
	}

	@Override
	public void stop() {
		// TODO Auto-generated method stub
		
	}
	
}
